package org.oschina.helper.index.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.oschina.Constants;
import org.oschina.helper.index.IndexHelper;
import org.oschina.helper.index.IndexResultBean;
import org.oschina.util.SolrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 索引实现类
 */
public class IndexHelperImpl implements IndexHelper {

	private final static Logger logger=LoggerFactory.getLogger(IndexHelperImpl.class);
	private Map<String,HttpSolrServer> server=new HashMap<String,HttpSolrServer>();
	private String root;
	
	@Override
	public <T> IndexResultBean<T> query(String path, String where, String[] sort, String[] order, int first, int max, Class<T> type)
	{
		try
		{
			Integer totalHits[]={0};
			List<T> result=SolrUtil.query(_getHttpSolrServer(path), where, sort, order, first, max, type, totalHits);
			IndexResultBean indexResult=new IndexResultBean();
			indexResult.setSum(totalHits[0]);
			indexResult.setResult(result);
			_showTerm(path,"search",where);
			return indexResult;
		}
		catch(Exception e)
		{
			logger.error("",e);
			return null;
		}
	}

	@Override
	public void remove(String path, String where)
	{
		try
		{
			SolrUtil.remove(_getHttpSolrServer(path), where);
			_showTerm(path,"remove",where);
		}
		catch(Exception e)
		{
			logger.error("",e);
		}
	}

	@Override
	public void write(String path, String[] fields, Object[] values)
	{
		try
		{
			SolrUtil.write(_getHttpSolrServer(path), fields, values);
		}
		catch(Exception e)
		{
			logger.error("",e);
		}
	}
	
	@Override
	public void update(String path, String where, String[] fields, Object[] values)
	{
		try
		{
			SolrUtil.update(_getHttpSolrServer(path), where, fields, values);
			_showTerm(path,"update",where);
		}
		catch(Exception e)
		{
			logger.error("",e);
		}
	}
	
	private HttpSolrServer _getHttpSolrServer(String path)
	{
		HttpSolrServer httpSolrServer=server.get(path);
		if(httpSolrServer==null)
		{
			httpSolrServer=SolrUtil.getHttpSolrServer(this.root+path);
			server.put(path, httpSolrServer);
		}
		return httpSolrServer;
	}
	
	private void _showTerm(String path,String type,String term)
	{
		if(!Constants.INDEX_SHOW_TERM)
			return;
		
		logger.info("\nshow_term:\npath : {}, {} : {}",path,type,term);
	}

	public String getRoot() {
		return root;
	}
	public void setRoot(String root) {
		this.root = root;
	}
}